/**
 * 租户管理相关功能
 */
import { mysql } from 'src-ssr/db/connect';
import TableHelper from 'src-ssr/db/tableHelper';
import * as tools from 'src-ssr/util/common';
import logs from 'src-ssr/util/logs';
import { Sequelize, Op, QueryTypes } from 'sequelize';
import models, { sequelize } from 'src-ssr/db/sequelize';
import moment from 'moment';
import shortid from 'shortid';
import md5 from 'md5';
import mDict from 'src-ssr/util/dictionary';

import * as singleUtils from 'src-ssr/controller/common/singleOperate';

import listConfig from 'app/search/manager/tenant/list.js';

const menuName = 'tenant';
const modelName = 'm_tenants';
const modelLabel = '租户信息';

// 列表
export const list = async (req, res) => {
  const { startRow, count, filter, sortBy, descending } = req.body;

  const where = await tools.assemblyWhere({
    filter,
    searchConfig: listConfig.search,
    fn: ({ where, field, search }) => {
      if (field === 'expire') {
        if (search === 'yes') {
          where.expire_time = { [Op.lt]: moment().unix() }
        } else {
          where.expire_time = { [Op.gt]: moment().unix() }
        }
      }
    }
  });
  where.id = { [Op.gt]: 0 }; // 取id大于0的租户

  const exclude = ['create_user_id', 'modify_user_id', 'history', 'uid'];
  // 只取单条数据
  if (filter && filter.id) {
    where.id = filter.id;
    exclude.splice(exclude.indexOf('history'), 1);
  }

  const order = sortBy ? [[sortBy, descending ? 'DESC' : 'ASC']] : [];

  const user = await tools.getLoginUser(req.get('Authorization').split(' ')[1]);
  const right = await tools.checkUserRight(user, menuName, ['data']);
  if (!right.data) { // 是否有查看全部的权限
    where.create_user_id = user.id;
  }

  let ret = { rows: [], count: 0 };
  try {
    ret = await models[modelName].findAndCountAll({
      attributes: {
        exclude,
        include: [[Sequelize.literal(`IFNULL((
          SELECT SUM(d.money)
          FROM t_sale_details d
          LEFT JOIN t_sales m ON m.uid = d.master_uid
          WHERE NOT ISNULL(m.consumer_uid) AND m.tenant_id = m_tenants.id
        ), 0)`), 'consumer_money'],
        [Sequelize.literal(`IFNULL((
          SELECT COUNT(DISTINCT consumer_uid)
          FROM t_sales m
          WHERE NOT ISNULL(m.consumer_uid) AND m.tenant_id = m_tenants.id
        ), 0)`), 'consumer_cnt'],
        [Sequelize.literal(`IFNULL((
          SELECT COUNT(id)
          FROM t_materials m
          WHERE m.sell=1 AND m.tenant_id = m_tenants.id
        ), 0)`), 'sell_cnt'],
        [Sequelize.literal(`IFNULL((
          SELECT COUNT(id)
          FROM m_shops m
          WHERE m.state=1 AND m.tenant_id = m_tenants.id
        ), 0)`), 'shop_state']]
      },
      include: [{
        model: models.m_users,
        attributes: ['nickname']
      }],
      where,
      order,
      offset: count ? startRow : undefined,
      limit: count || undefined,
      group: count ? `${modelName}.id` : undefined
    });
  } catch (e) {
    console.error(modelLabel + '列表出错', e);
  }

  function calculateDaysDifference (expirationTimestamp) {
    // 将时间戳转换为 Moment.js 对象
    const currentTime = moment();
    const expirationTime = moment(expirationTimestamp, 'X');

    // 计算时间差（以毫秒为单位）
    const diffMilliseconds = expirationTime.diff(currentTime);

    // 将时间差转换为天数
    const diffDays = Math.abs(moment.duration(diffMilliseconds).asDays());

    if (diffMilliseconds > 0) {
      // 当前时间戳小于过期时间戳
      return `${Math.floor(diffDays)}天`;
    } else {
      // 当前时间戳大于过期时间戳
      return `已过期${Math.floor(diffDays)}天`;
    }
  }

  // 处理其它数据
  const rows = [];
  ret.rows.forEach(row => {
    const jsonRow = row.toJSON();

    jsonRow.per_money = jsonRow.consumer_cnt > 0 ? (jsonRow.consumer_money / jsonRow.consumer_cnt).toFixed(2) : '0.00';
    jsonRow.consumer_money = Number(jsonRow.consumer_money).toFixed(2);

    jsonRow.expire = calculateDaysDifference(jsonRow.expire_time);
    jsonRow.users = row.m_users.length;
    jsonRow._owner = row.create_user_id == user.id; // 是否为拥有者
    rows.push(jsonRow);
  });

  if (filter && filter.id) {
    return rows.length > 0 ? rows[0] : {};
  } else {
    res.json({
      data: rows,
      rowsNumber: typeof ret.count === 'object' ? ret.count.length : ret.count
    });
  }
};

// 详细信息
export const detail = async (req, res) => {
  req.body.filter = { id: req.body.id };

  const ret = await list(req);

  res.json(ret);
};

/**
 * 新增
 */
export const create = async (req, res) => {
  const { formData } = req.body;
  formData.expire_time = moment().add(6, 'day').endOf('day').format('X'); // 初始7天有效期

  // 创建租户信息
  const ret = await singleUtils.createData(modelName, modelLabel, menuName, req);

  const tenant_id = ret.id;
  // 创建租户用户
  const user = await tools.getLoginUser(req.get('Authorization').split(' ')[1]);
  const data = TableHelper.filterField('m_users', formData.user);
  data.tenant_id = tenant_id;
  data.salt = shortid.generate();
  data.password = md5((data.password || 'mdy123456') + data.salt);// 空密码设为mdy123456
  data.create_time = parseInt(Date.now() / 1000);
  data.create_user_id = user.id;
  data.create_user_name = user.nickname;
  data.create_ip = tools.getIP(req);

  const newUser = await models.m_users.create(data);

  // 取菜单中的默认权限
  const defaultRights = await tools.defaultRights('t', true);

  await models.m_users.update({ rights: defaultRights.rights, hash: defaultRights.hash }, { where: { id: newUser.id } });

  // 为租户创建表分区
  await sequelize.query('CALL f_add_table_partition(:tenantId)', {
    replacements: { tenantId: tenant_id }, // 参数替换
    type: Sequelize.QueryTypes.RAW // 使用RAW查询类型来执行原生SQL
  });

  // 为租户添加默认货物所有分类
  await models.t_material_catalog.create({
    tenant_id,
    catalog_code: '',
    catalog_name: '所有分类',
    parent_id: '-1'
  });

  mDict.refresh(tenant_id); // 刷新租户专属字典

  res.json(ret);
};

/**
 * 更新
 */
export const update = async (req, res) => {
  const ret = await singleUtils.updateData(modelName, modelLabel, menuName, req);
  res.json(ret);
};

/**
 * 删除
 */
export const destroy = async (req, res) => {
  const ret = await singleUtils.destroyData(modelName, modelLabel, menuName, req);
  if (ret.result === 'ok') {
    const { id } = req.body;
    // 租户分区表删除相应分区
    await sequelize.query('CALL f_delete_table_partition(:tenantId)', {
      replacements: { tenantId: id }, // 参数替换
      type: Sequelize.QueryTypes.RAW // 使用RAW查询类型来执行原生SQL
    });

    // 管理表删除租户数据
    await sequelize.query('CALL f_delete_tenant_data(:tenantId)', {
      replacements: { tenantId: id }, // 参数替换
      type: Sequelize.QueryTypes.RAW // 使用RAW查询类型来执行原生SQL
    });
  }
  res.json(ret);
};
